import React, { useState, useEffect, useCallback } from 'react';
import { Select, Modal, Input } from 'antd';
import IconFont from '@/components/IconFont';
import { useDictionary } from '@/hooks';
import { size } from 'lodash';
import { guid } from '@/utils/utils';
import styles from './index.less';

// 主管称呼下拉组件
const { Option } = Select;

const AppellationSelect = React.forwardRef(
    ({ value, onChange = () => {}, onSelect, allowCustom = false, customMaxLength = 50, ...rest }, ref) => {
        const [visible, setVisible] = useState();
        const [selectOpen, setSelectOpen] = useState();
        const [selectValue, setSelectValue] = useState();
        const [customInput, setCustomInput] = useState();
        const [leaderTitleTypeList = []] = useDictionary('leaderTitle', { useCache: false });

        useEffect(() => {
            const { key, label } = value || {};
            if (key === undefined && label === undefined) {
                setSelectValue(undefined);
            } else {
                setSelectValue(value);
            }
        }, [value]);

        // 将自定义的值加入到列表
        const addInTypeList = useCallback(
            addValue => {
                if (size(addValue) > 0) {
                    const key = guid('new');
                    const listLen = size(leaderTitleTypeList);
                    if (listLen === 0) {
                        leaderTitleTypeList.push({ text: addValue, value: key });
                    } else {
                        // 判断是否已经存在相同的值
                        const hasInList = leaderTitleTypeList.find(item => item.text === addValue);
                        if (!hasInList) {
                            leaderTitleTypeList.push({ text: addValue, value: key });
                        }
                    }
                    setCustomInput();
                }
            },
            [leaderTitleTypeList]
        );

        useEffect(() => {
            if (selectValue && leaderTitleTypeList) {
                const { label, key } = selectValue || {};
                if (size(key) === 0 && size(label) > 0) {
                    addInTypeList(label);
                }
            }
        }, [selectValue, leaderTitleTypeList, addInTypeList]);

        // 处理输出的结构，主要是移除自定义新增的key
        const outValue = (fn, outSelectValue = {}, option = {}) => {
            if (fn) {
                let isNew = false;
                const { value: tempValue } = option?.props || {};
                if (tempValue && tempValue.indexOf('new') > -1) {
                    isNew = true;
                }

                const { key, label } = outSelectValue;
                let outTempValue = { key: isNew ? '' : key, label };
                if (label === undefined && key === undefined) {
                    outTempValue = undefined;
                }
                fn(outTempValue, option, isNew);
            }
        };

        return (
            <div ref={ref}>
                <Select
                    value={selectValue}
                    onChange={(e, option) => {
                        outValue(onChange, e, option);
                    }}
                    defaultOpen={visible}
                    allowClear
                    loading={size(leaderTitleTypeList) === 0}
                    showSearch
                    placeholder="请选择/请输入"
                    optionFilterProp="children"
                    getPopupContainer={triggerNode => triggerNode.parentElement}
                    {...rest}
                    {...selectOpen}
                    labelInValue
                    dropdownStyle={{ zIndex: 1000 }}
                    onSelect={(e, option) => {
                        outValue(onSelect, e, option);
                    }}
                    dropdownRender={menu => (
                        <div className={styles.dropdownWrap}>
                            {menu}
                            {allowCustom && (
                                <div
                                    className={styles.customBtnWrap}
                                    onMouseDown={e => e.preventDefault()}
                                    onClick={() => {
                                        setSelectOpen({ open: true });
                                        setVisible(true);
                                    }}
                                >
                                    <IconFont icon="plus" style={{ marginRight: 5, fontSize: 12 }} /> 自定义
                                </div>
                            )}
                        </div>
                    )}
                >
                    {leaderTitleTypeList?.map(item => (
                        <Option key={item.value} value={item.value}>
                            {item.text}
                        </Option>
                    ))}
                </Select>
                <Modal
                    title="自定义称呼"
                    visible={visible}
                    onOk={() => {
                        addInTypeList(customInput);
                        setVisible(false);
                        setSelectOpen();
                    }}
                    onCancel={() => {
                        setVisible(false);
                        setSelectOpen();
                    }}
                >
                    <div className={styles.custModalForm}>
                        <span>主管称呼：</span>
                        <Input
                            maxLength={customMaxLength}
                            value={customInput}
                            onChange={e => {
                                setCustomInput(e.target.value);
                            }}
                            placeholder="请输入"
                            style={{ flex: 1 }}
                        />
                    </div>
                </Modal>
            </div>
        );
    }
);

export default AppellationSelect;
